package com.example.upload;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.up.BlockSize;
import com.example.up.OKHttp;
import com.example.up.Upload;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.Request;

public class MainActivity extends AppCompatActivity {

    private static String TAG = "Test";
    private TextView mText;
    private TextView mText2;


    private static String URL = "http://10.0.2.2:8080/Test/";
    private static String URL22 = "http://192.168.1.132:8080/Test/";
    //    private static String URL2= "http://192.168.1.51:8080/Test/";
    private static String URL2 = "http://192.168.23.1:8080/Test/";
//    private static String URL2 = "http://192.168.0.43:8080/Test/";


    private static String URL3 = URL2 + "upload!preUpload";

    private static String URL4 = URL2 + "upload!upload";


    private Button mUploadBt;
    private EditText blockSize;
    private TextView mText3;
    private EditText mMaxRequest;
    private EditText mMaxHostRequest;


    private boolean upLoading = false;

    private File file;


    private static int n = 3;
    private static int N = 3;

    private Vibrator vibrator;
    long[] pattern = {100, 400, 100, 400};

    private int avtime;
    private int avSudu;

    private List<Integer> mTime = new ArrayList<>();
    private List<Integer> mSudu = new ArrayList<>();

    private boolean once = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        mText = (TextView) findViewById(R.id.text);
        mUploadBt = (Button) findViewById(R.id.uploadBt);
        mText2 = (TextView) findViewById(R.id.text2);
        blockSize = (EditText) findViewById(R.id.blockSize);
        mText3 = (TextView) findViewById(R.id.text3);
        mMaxRequest = (EditText) findViewById(R.id.maxRequest);
        mMaxHostRequest = (EditText) findViewById(R.id.maxHostRequest);


    }

    private void log(String str) {
        Log.d(TAG, "--------" + str);
    }

    public void select(View view) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("video/*;image/*");//同时选择视频和图片
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, 1);
    }

    public void upload(View view) {
        avtime = 0;
        avSudu = 0;
        mTime.clear();
        mSudu.clear();
        n = 3;
        if (!upLoading) {
            upLoading = true;
            mUploadBt.setText("pause");
            upload();
        } else {
            upLoading = false;
            mUploadBt.setText("continue");
            pause();
        }


    }

    private void pause() {
        Upload.pause(file.getName());
    }


    void upload() {
        if (!TextUtils.isEmpty(blockSize.getText())) {
            float size = Float.parseFloat(blockSize.getText().toString());
            BlockSize.setBlockSize((int) (size * 1024 * 1024));
        }

        if (!TextUtils.isEmpty(mMaxRequest.getText())) {
            int size = Integer.parseInt(mMaxRequest.getText().toString());
            Upload.setMaxRequest(size);
        }

        if (!TextUtils.isEmpty(mMaxHostRequest.getText())) {
            int size = Integer.parseInt(mMaxHostRequest.getText().toString());
            Upload.setOkMaxHostRequest(size);
        }


        String fileKey = "file";
        Map<String, String> parms = new HashMap<>();
        parms.put("username", "yhao");
        parms.put("fileName", file.getName());
        final long[] p = new long[]{0L};
        final long time = System.currentTimeMillis();
        once = true;
        Upload.upLoad(URL4, file, fileKey, parms, new OKHttp.ResultCallback<String>() {

                    @Override
                    public void onError(Request request, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
//                        Log.d(TAG, "onResponse: " + response);

                    }
                }, new OKHttp.ProgressListener() {
                    @Override
                    public void onProgress(long fileLength, long readBytesCount, boolean blockReadDone, long blockStartTime) {
                        long pp = readBytesCount * 100L / fileLength;
                        //过滤重复进度，使进度更新平滑
                        if (p[0] != pp) {
                            p[0] = pp;
                            mText2.setText("fileLength:" + fileLength / 1000.0 + "KB" + "\n" +
                                    "进度：" + p[0] + ""
                            );
                        }
                        if (once && p[0] == 100) {
                            float t = (System.currentTimeMillis() - time);
                            float s = (fileLength / t);
                            avtime += t;
                            mTime.add((int) t);
                            mSudu.add((int) s);
                            avSudu += s;
                            String result = "fileLength:" + fileLength / 1000.0 / 1000.0 + "MB" +
                                    " block：" + BlockSize.getBlockSize() / 1000.0 + "KB" +
                                    " time：" + (t / 1000.0) + "秒" +
                                    " 速度：" + s + "KB/S";
                            Log.d(TAG, result);
                            mText2.setText(result);
                            mUploadBt.setText("upload");
                            upLoading = false;
                            n--;
//                            if (n > 0) {
//                                upload();
//                                return;
//                            }
//                            Log.d(TAG, N + "次 平均耗时：" + avtime / N + "  平均速度:" + avSudu / N + " max/min耗时：" + Collections.max(mTime) +
//                                    "/" + Collections.min(mTime) + " max/nin速度：" + Collections.max(mSudu) + "/" + Collections.min(mSudu));
//                            vibrator.vibrate(pattern, -1);
                            once = false;
                        }
                    }
                }, new OKHttp.RequestInfoListener() {
                    @Override
                    public void onRequest(int maxRequest, int maxHostRequest, int runningRequest, int queuedRequest) {
                        mText3.setText("maxRequest：" + maxRequest + "\n" +
                                "maxHostRequest：" + maxHostRequest + "\n" +
                                "runningRequest：" + runningRequest + "\n" +
                                "queuedRequest：" + queuedRequest);
                    }
                }
        );
    }


    public void loginTest(View view) {
        Map<String, String> parms = new HashMap<>();
        parms.put("username", "yhao");
        OKHttp.postAsyn(URL2 + "logina", new OKHttp.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Toast.makeText(MainActivity.this, "connect success", Toast.LENGTH_SHORT).show();

            }
        }, parms);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续
            Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
            int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            String path = actualimagecursor.getString(actual_image_column_index);
            mText.setText(path);
            file = new File(path);
            if (!file.exists()) {
                log("文件不存在");
                return;
            }
            mText2.setText("fileLength:" + file.length() / 1000.0 + "KB");
        }
    }
}
